import xlrd
import sys
import json
from pymongo import MongoClient

def dump_excel(file, dbname):
    print("save to % %", file, dbname)
    # 连接数据库
    client = MongoClient("mongodb://")
    db = client.yqsl
    account = db[dbname]
    data = xlrd.open_workbook(file)
    table = data.sheets()[0]
    # 读取excel第一行数据作为存入mongodb的字段名
    rowstag = table.row_values(0)
    nrows = table.nrows
    returnData = {}
    for i in range(1,nrows):
        # 将字段名和excel数据存储为字典形式，并转换为json格式
        returnData[i] = json.dumps(dict(zip(rowstag,table.row_values(i))))
        # 通过编码还原数据
        returnData[i] = json.loads(returnData[i])
        account.insert_one(returnData[i])
    return returnData

if __name__ == '__main__':
    dump_excel(sys.argv[1], sys.argv[2])
    
